package com.lf.web.service.system.menu;

import com.lf.data.Cluster;
import com.lf.data.ClusterUtil;
import com.lf.web.service.ResponseCode;
import com.lf.web.service.ResponseInfo;
import com.lf.web.service.ServiceSupport;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MenuAddService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(MenuAddService.class);
    private MenuDAO menuDAO;
    private List<Cluster> menus = null;

    public void setMenuDAO(MenuDAO menuDAO) {
        this.menuDAO = menuDAO;
    }

    public String execute() {
        String type = form.getString("type");
        if ("save".equals(type)) {
            return save();
        } else {
            menus = menuDAO.find(null, null, null);
            context.put("parentId", form.getString("parentId"));
            context.put("menus", menus);
            context.put("check", ClusterUtil.getCheck(Menu.class));
            return "add";
        }
    }

    private String save() {
        Menu menu = new Menu();
        boolean result = form.getCluster(menu);
        LOGGER.debug("添加菜单：" + menu);
        if (result) {
            ResponseInfo rj = new ResponseInfo();
            String parentid = menu.getString(Menu.PARENT_ID);
            List parent;
            if (parentid == null || "".equals(parentid)) {
                parent = new ArrayList();
                menu.remove(Menu.PARENT_ID);
            } else {
                Cluster cluster = menuDAO.findById(parentid);
                if (cluster.isEmpty()) {
                    rj.setCode(ResponseCode.EXIST_NOT);
                    out(rj);
                    return NONE;
                }
                parent = cluster.getList(Menu.PARENT);
                menu.put(Menu.PARENT_ID, cluster.get(Menu.ID));
            }
            String id = menu.setId();
            menu.put(Menu.PARENT, parent);
            menu.put(Menu.DEEP, parent.size());
            menu.put(Menu.CREATED, new Date());
            menuDAO.insert(menu);
            rj.setCode(ResponseCode.FINISH);
            rj.put("id", id);
            out(rj);
        } else {
            error(404);
            LOGGER.error("非法添加菜单：" + menu);
        }
        return NONE;
    }

}
